﻿using System;
using System.Linq;
using uTrade.Common;
using uTrade.Core;

namespace uTrade.Data.DataAccess.Futures
{
    public class DataAccessService
    {
        //数据处理功能模块
        private static DataProcess _dataProcess;

        private string server_addr = "broadcast.eicp.net:55881";

        public DataAccessService()
        {
            _dataProcess = new DataProcess(server_addr);
        }

        public TransDatas GetData(string inst, DateTime begin, DateTime end)
        {
            TransDatas transBars = new TransDatas();
            transBars.Interval = (int)1;
            transBars.Instrument = inst;

            //需处理成按合约取品种(期权规则与期货不同)
            Instrument instInfo;
            Product procInfo;
            if (!_dataProcess.InstrumentInfo.TryGetValue(inst, out instInfo) || !_dataProcess.ProductInfo.TryGetValue(instInfo.ProductID, out procInfo))
            {
                uLog.LogError("无合约对应的品种信息");
                return null;
            }
            transBars.InstrumentInfo = new InstrumentInfo
            {
                InstrumentID = inst,
                ProductID = instInfo.ProductID,
                PriceTick = procInfo.PriceTick,
                VolumeMultiple = procInfo.VolumeTuple,
            };
            var sbegin = begin.ToString("yyyyMMdd");
            var send = end.ToString("yyyyMMdd");
            var bars = _dataProcess.QueryMin(inst, sbegin, send).Select(n => new Bar
            {
                DateTime = DateTime.ParseExact(n._id, "yyyy-MM-dd HH:mm:ss", null),
                //TradingDay = int.Parse(n.TradingDay),
                Open = n.Open,
                High = n.High,
                Low = n.Low,
                Close = n.Close,
                Volume = n.Volume,
                OpenInterest = n.OpenInterest,
            }).ToArray();

            transBars.LoadData(bars);
            return transBars;
        }

        public static string[] GetInst()
        {
            var listInst = _dataProcess.InstrumentInfo.Select(n => n.Key).ToList();
            listInst.Sort();
            return listInst.ToArray();
        }
    }
}